package com.zmx.patients.view.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import com.google.gson.Gson;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.avchatkit.model.Accounts;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.model.AVChatChannelInfo;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.adapter.MeetingAdapter;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.Meeting;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.view.util.MyDialog;
import com.zmx.patients.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ExpertConsultationActivity extends BaseActivity {


    @BindView(R.id.reView)
    RecyclerView reView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private MeetingAdapter adapter;
    private List<Meeting> lists;
    private View mEmptyLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_expert_consultation;
    }

    @Override
    protected void initViews() {

        setToolbar(R.id.tool_bar);
        ButterKnife.bind(this);

        mEmptyLayout = findViewById(R.id.empty);
        adapter = new MeetingAdapter(this,handler);
        lists = new ArrayList<>();
        reView.setLayoutManager(new LinearLayoutManager(this));
        reView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                userAddMeeting(lists.get(listPosition).getId() + "");

            }
        });

        // 开启自动加载功能
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            meeting();
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            //刷新加载
            refreshLayout.finishLoadMore(true);

        });

        //触发自动刷新
        refreshLayout.autoRefresh();


    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:
                    lists.clear();
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1) {
                            Gson gson = new Gson();
                            JSONArray array = object.getJSONArray("data");
                            for (int i = 0; i < array.length(); i++) {

                                Meeting m = gson.fromJson(array.getJSONObject(i).toString(), Meeting.class);
                                lists.add(m);
                            }
                            adapter.setListAndNotifyDataSetChanged(lists);
                        }

                        if (lists.size() > 0) {
                            mEmptyLayout.setVisibility(View.GONE);
                        } else {
                            mEmptyLayout.setVisibility(View.VISIBLE);
                        }
                        refreshLayout.finishRefresh(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Gson gson = new Gson();

                        if (object.getInt("code") == 1) {

                            JSONObject data = object.getJSONObject("data");

                            ArrayList<Accounts> accounts = new ArrayList<>();
                            JSONArray array = data.getJSONArray("accid");

                            for (int i = 0; i < array.length(); i++) {

                                Accounts as = gson.fromJson(array.get(i).toString(),Accounts.class);
                                accounts.add(as);

                            }

                            int roomID = data.getInt("meeting_id");

                            AVChatManager.getInstance().createRoom(roomID + "", "家属", new AVChatCallback<AVChatChannelInfo>() {
                                @Override
                                public void onSuccess(AVChatChannelInfo avChatChannelInfo) {

                                    Log.e("成功", "成功");

                                    AVChatKit.outgoingTeamCall(mActivity, true, "1", roomID + "", accounts, "多方通话");

                                }

                                @Override
                                public void onFailed(int code) {

                                    Log.e("错误码", "错误码" + code);

                                    AVChatKit.outgoingTeamCall(mActivity, true, "1", roomID + "", accounts, "多方通话");

                                }

                                @Override
                                public void onException(Throwable exception) {

                                    Log.e("错误提示", "错误提示" + exception.toString());
                                }
                            });

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
                case 3:

                    Log.e("参数id","参数id"+msg.obj.toString());

                    String meeting_id = msg.obj.toString();

                    View view = getLayoutInflater().inflate(R.layout.dialog_meeting, null);

                    MyDialog mMyDialog = new MyDialog(mActivity, 0, 0, view, R.style.DialogTheme);
                    mMyDialog.setCancelable(true);
                    mMyDialog.show();
                    Button cancel = view.findViewById(R.id.cancel);
                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mMyDialog.dismiss();
                        }
                    });
                    Button add = view.findViewById(R.id.add);
                    add.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            userAddMeeting(meeting_id);
                            mMyDialog.dismiss();
                        }
                    });
                    break;
            }

        }
    };


    public void userAddMeeting(String meeting_id) {

        List<String> ls = new ArrayList<>();
        ls.add(meeting_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "userAddMeeting");
        params.put("data[meeting_id]", meeting_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app", params, handler, 2, 404);

    }

    public void meeting() {

        List<String> ls = new ArrayList<>();
        ls.add("10");
        ls.add("1");
        ls.add("0");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "meeting");
        params.put("data[number]", "10");
        params.put("data[row]", "1");
        params.put("data[type]", "0");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app", params, handler, 1, 404);

    }


}

